<template>
    <div class="website-config">
        <slot v-if="loading">
            <div class="loading">加载中...</div>
        </slot>
        <slot v-else :config="configData"></slot>
    </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineExpose } from 'vue'
import { getFrontendConfig } from '@/api/bk/website'

const props = defineProps({
    // 需要获取的配置键名，不传则获取全部
    keys: {
        type: Array,
        default: () => []
    }
})

const loading = ref(true)
const configData = ref({})

function getWebsiteConfig() {
    loading.value = true
    return getFrontendConfig().then(res => {
        if (res.code === 200) {
            const configs = res.data || []

            // 转换配置数据为键值对形式，方便使用
            const configObj = configs.reduce((acc, curr) => {
                acc[curr.configKey] = curr.configValue
                return acc
            }, {})

            // 如果指定了keys，只保留需要的配置
            if (props.keys.length > 0) {
                const filteredConfig = {}
                props.keys.forEach(key => {
                    if (configObj[key] !== undefined) {
                        filteredConfig[key] = configObj[key]
                    }
                })
                configData.value = filteredConfig
            } else {
                configData.value = configObj
            }
        }
        loading.value = false
        return configData.value
    }).catch(() => {
        loading.value = false
        return {}
    })
}

// 暴露给父组件的方法
defineExpose({
    getWebsiteConfig,
    refresh: getWebsiteConfig
})

onMounted(() => {
    getWebsiteConfig()
})
</script>

<style scoped>
.loading {
    text-align: center;
    padding: 20px 0;
    color: #999;
}
</style>